#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys, os;sys.path.append(os.getcwd())

from fdfs_client.client import Fdfs_client, get_tracker_conf

def clent():
    tracker_path = get_tracker_conf('config/client.conf')
    client = Fdfs_client(tracker_path)
    return client

'''
@return dict {
'Group name' : group_name_bytes,
'Remote file_id' : remote_file_id_bytes,
'Status' : 'Upload successed.',
'Local file name' : local_file_name,
'Uploaded size' : upload_size,
'Storage IP' : storage_ip_bytes
} if success else None
'''
def upload(filename):
    ret = clent().upload_by_filename(filename)
    return ret
'''
@return dict {
'Group name' : group_name_bytes,
'Remote file_id' : remote_file_id_bytes,
'Status' : 'Upload successed.',
'Local file name' : local_file_name,
'Uploaded size' : upload_size,
'Storage IP' : storage_ip_bytes
} if success else None
'''
def upload_by_buffer(buffer):
    ret = clent().upload_by_buffer(buffer)
    return ret

'''
@return dict {
'Remote file_id' : remote_file_id_bytes,
'Content' : local_file_name,
'Download size' : upload_size,
'Storage IP' : storage_ip_bytes
}
'''
def download(filename, file_id):
    ret = clent().download_to_file(filename, file_id.encode('utf-8'))
    file_id = ret.get('Remote file_id', b'').decode()
    # filename = ret.get('Content')
    # 155.19KB
    size = ret.get('Download size')
    ip = ret.get('Storage IP', b'').decode()
    return ret

'''
return tuple ('Delete file successed.', remote_file_id_bytes, storage_ip_bytes)
'''
def delete(file_id):
    ret = clent().delete_file(file_id.encode('utf-8'))
    return ret

if __name__ == '__main__':
    help_msg = '''\
        Usage:python3 %s {option} filename [file_id]
        -u: filename         | upload filename
        -d: filename file_id | download filename by file_id
        -D: file_id          | Delelte filename by file_id
        ---------------------------------------------------------
        [require py3Fdfs]
        pip3 install py3Fdfs==2.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
        '''    % sys.argv[0]
    if len(sys.argv) < 2:
        print(help_msg)
    else:
        if '-u' == sys.argv[1]:
            filename = sys.argv[2]
            if not os.path.exists(filename):
                raise BaseException('file %s not exists' % filename)
            upload(filename)
            exit(0)
        if '-d' == sys.argv[1]:
            filename = sys.argv[2]
            file_id = sys.argv[3]
            download(filename, file_id)
            exit(0)
        if '-D' == sys.argv[1]:
            file_id = sys.argv[2]
            delete(file_id)
            exit(0)
        print(help_msg)
